<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleCloseDialog"
    @open="handleDialogOpen"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button
        type="primary"
        size="small"
        @click="assignRole"
      >确定</el-button>
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
// 获取角色列表的组件
import { getRoleList } from '@/api/setting'
// 获取用户信息根据id
import { getUserDetailById } from '@/api/user'
// 新增角色接口
import { assignRole } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 1. 选中的复选框内容
      checkList: [],
      // 2. 所有的角色列表
      roleList: [],
      // 3. 加载圈
      loading: false
    }
  },
  methods: {
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },
    // 2. 弹窗打开时触发
    handleDialogOpen() {
    //   this.getRoleList()
    //   this.getUserDetailById()
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      })
    },
    // 3. 获取角色列表
    async getRoleList() {
      const { rows } = await getRoleList(1, 9999)
      //   存入校色列表
      this.roleList = rows
    },
    // 4. 根据用户id获取用户的角色
    async getUserDetailById() {
      const { roleIds } = await getUserDetailById(this.userId)
      console.log(roleIds)
      this.checkList = roleIds
    },
    // 5. 点击了分配角色按钮
    async assignRole() {
      await assignRole(this.userId, this.checkList)
      this.$message.success('分配角色成功')
      // 关闭弹窗
      this.handleCloseDialog()
    }
  }
}
</script>

  <style>

  </style>
